#include "login.h"
#include "ui_login.h"
#include "../data/account.h"
#include "../utility/connector.h"

Login::Login(QWidget *parent, Connector *connector, Account *account) :
    QDialog(parent),connector(connector),account(account),
    ui(new Ui::Login) {
    qDebug()<<"Login::Login called.";
    ui->setupUi(this);
    setModal(true);
    setAttribute(Qt::WA_DeleteOnClose,false);
    connect(ui->pushButton_login,SIGNAL(clicked(bool)),
            this,SLOT(login()));
    connect(ui->commandLinkButton_goregister,SIGNAL(clicked(bool)),
            this,SLOT(enroll()));
    connect(ui->commandLinkButton_forgetpword,SIGNAL(clicked(bool)),
            this,SLOT(reset()));
    connect(this,SIGNAL(rejected()),
            this,SLOT(abort()));
    qDebug()<<"Login::Login returned.";
}

Login::~Login() {
    qDebug()<<"Login::~Login called.";
    delete ui;
    qDebug()<<"Login::~Login returned.";
}

void Login::push() {
    qDebug()<<"Login::push called.";
    if(account->username!=nullptr)
        ui->lineEdit_account->setText(*account->username);
    if(account->password!=nullptr)
        ui->lineEdit_password->setText(*account->password);
    ui->checkBox_autologin->setChecked(autoLogin);
    ui->checkBox_rememberpword->setChecked(storePassword);
    qDebug()<<"Login::push returned.";
}

void Login::abort() {
    qDebug()<<"Login::abort called.";
    state=State::Aborted;
    qDebug()<<"Login::abort returned.";
}

void Login::enroll() {
    qDebug()<<"Login::enroll called.";
    state=State::ToRegister;
    accept();
    qDebug()<<"Login::enroll returned.";
}

void Login::reset() {
    qDebug()<<"Login::reset called.";
    state=State::Aborted;
    accept();
    qDebug()<<"Login::reset returned.";
}

void Login::login() {
    qDebug()<<"Login::login called.";
    QString username=ui->lineEdit_account->text();
    QString password=ui->lineEdit_password->text();
    QString loginState;
    State s=connector->login(&username,&password,&loginState);
    if(s!=State::Succeeded) {
        return;
    }
    if(loginState!="Success"&&loginState!="Admin") {
        return;
    }
    account->setUsername(new QString(username));
    account->setPassword(new QString(password));
    account->isAdmin=loginState=="Admin";
    state=State::Succeeded;
    storePassword=ui->checkBox_rememberpword->isChecked();
    autoLogin=ui->checkBox_autologin->isChecked();
    accept();
    qDebug()<<"Login::login returned.";
}
